Shell 脚本中的 if 条件判断 |
您所在的位置:网站首页 › shell 等于判断 › Shell 脚本中的 if 条件判断 |
前言 if...else... 可以说是我们在编程中最常见的条件判断语句了,那么在 Shell 中如何使用呢?如何判断两个数值相等?如何判断一个文件是否存在?跟随这篇文章,一起来学习吧! 条件判断格式在 Shell 中有两种判断格式,分别如下: # 1. 第一种 test 条件判断式 # 2. 第二种,注意括号两端必须有空格 [ 条件判断式 ]第二种方式相当于第一种的简化。那么我们如何知道一个条件判断语句是否为真呢?其实在 Bash中的变量类型,还有这两种! 的预定义变量部分 ,我们学习过如何判断一个命令是否执行成功,即 $? 是否等于 0,0表示执行成功,否则表示上个命令失败,条件判断也是使用这种方式。 # 查看文件列表 [root@VM-0-5-centos ~]# ls if.sh student.txt test.sh # -e 文件名,用于判断文件是否存在 [root@VM-0-5-centos ~]# test -e if.sh [root@VM-0-5-centos ~]# echo $? 0 [root@VM-0-5-centos ~]# test -e if.ssss [root@VM-0-5-centos ~]# echo $? 1 # 换个姿势,再来测试一遍 [root@VM-0-5-centos ~]# [ -e if.sh ] [root@VM-0-5-centos ~]# echo $? 0 [root@VM-0-5-centos ~]# [ -e if.ssss ] [root@VM-0-5-centos ~]# echo $? 1 if 语句 if 开头,fi 结尾[ 条件判断 ] 就是使用 test 命令判断,两端必须有空格if 如果 和 then 在一行,需要加 ;单分支 if [ 条件判断式 ];then 命令 fi 或者 if [ 条件判断式 ] then 命令 fi双分支 if [ 条件判断式 ] then 命令 else 命令 fi多分支 if [ 条件判断式1 ] then 命令 elif [ 条件判断式2 ] then 命令 ... else 命令 fi 条件判断类型 按照文件类型进行判断![]() 为了测试各种判断类型方便,我们可以直接使用如下方式测试,避免每次写脚本了。 # 一个命令正确执行,输出yes,否则输出no [root@VM-0-5-centos ~]# [ -e student.txt ] && echo 'yes' || echo 'no' yes [root@VM-0-5-centos ~]# [ -e sss ] && echo 'yes' || echo 'no' no [root@VM-0-5-centos ~]# [ -d mydir/ ] && echo 'yes' || echo 'no' yes [root@VM-0-5-centos ~]# [ -d student.txt ] && echo 'yes' || echo 'no' no 按照文件权限进行判断![]() ![]() ![]() ![]() if 判断中对于变量的处理,需要加引号,如果没有加双引号,可能会在判断含空格的字符串变量的时候产生错误。 [root@VM-0-5-centos ~]# name="" # 不见引号,判断出的 name 是非空,其实是空[root@VM-0-5-centos ~]# [ -n $name ] && echo 'yes' || echo 'no'yes # 加上引号就对了[root@VM-0-5-centos ~]# [ -n "$name" ] && echo 'yes' || echo 'no'no [root@VM-0-5-centos ~]# name1=hello[root@VM-0-5-centos ~]# name2=world[root@VM-0-5-centos ~]# [ "$name1" != "$name2" ] && echo 'yes' || echo 'no'yes[root@VM-0-5-centos ~]# [ "$name1" == "$name2" ] && echo 'yes' || echo 'no'no 多重条件判断![]() 本篇文章首先介绍了条件判断的格式以及原理,然后介绍了 if 语句的格式,最后介绍了多个条件判断类型。内容比较多,熟能生巧,快操练起来吧! 更多个人博客: https://lifelmy.github.io/ 微信公众号:漫漫Coding路 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |